package com.zhugang.week13.recursion;

import java.util.HashMap;
import java.util.Map;

/**
 * @program algorithms
 * @description: waysToStep
 * @author: chanzhugang
 * @create: 2022/11/17 10:25
 */
public class WaysToStep {

    /**
     * 面试题 08.01 三步问题
     * https://leetcode.cn/problems/three-steps-problem-lcci/
     *
     * @param n
     * @return
     */
    Map<Integer, Integer> cache = new HashMap<>();
    int mod = 1000000007;

    public int waysToStep(int n) {
        /**
         * 递归 + 缓存
         */
        if (n == 1) return 1;
        if (n == 2) return 2;
        if (n == 3) return 4;
        if (cache.containsKey(n)) {
            return cache.get(n);
        }
        // 前几个可能计算的比较大，需要取模
        int ways = ((waysToStep(n - 1) + waysToStep(n - 2)) % mod + waysToStep(n - 3)) % mod;
        cache.put(n, ways);
        return ways;
    }

    public int waysToStep2(int n) {
        /**
         * 非递归实现
         * 动态规划：dp[n] = dp[n - 1] + dp[n - 2] + dp[n - 3]
         */
        if (n == 1) return 1;
        if (n == 2) return 2;
        if (n == 3) return 4;
        int[] dp = new int[n + 1];
        dp[1] = 1;
        dp[2] = 2;
        dp[3] = 4;
        for (int i = 4; i <= n; i++) {
            // 状态转移方程
            dp[i] = ((dp[i - 1] + dp[i - 2]) % mod + dp[i - 3]) % mod;
        }
        return dp[n];
    }

    public int waysToStep3(int n) {
        /**
         * 非递归写法，错位往后移动
         */
        if (n == 1) return 1;
        if (n == 2) return 2;
        if (n == 3) return 4;
        int a = 1;
        int b = 2;
        int c = 4;
        int d = 0;
        for (int i = 4; i <= n; i++) {
            d = ((c + b) % mod + a) % mod;
            a = b;
            b = c;
            c = d;
        }
        return d;
    }
}